package com.zjlanyun.eplus.view.report;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.LinearLayout;

import com.aihook.tableview.lib.TableDataAdapter;
import com.aihook.tableview.lib.TableFixHeaders;
import com.gigamole.navigationtabstrip.NavigationTabStrip;
import com.yanzhenjie.nohttp.rest.Response;
import com.zjlanyun.eplus.R;
import com.zjlanyun.eplus.network.WebApi;
import com.zjlanyun.eplus.nohttp.HttpRequest;
import com.zjlanyun.eplus.nohttp.SimpleHttpListener;
import com.zjlanyun.eplus.view.report.adapter.GalleryAdapter;
import com.zjlanyun.eplus.view.report.custom.SpaceItemDecoration;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zjlanyun.eplus.view.report.UtilConstants.CLASS_BOTTOM;
import static com.zjlanyun.eplus.view.report.UtilConstants.CLASS_LEFT;
import static com.zjlanyun.eplus.view.report.UtilConstants.CLASS_RIGHT;
import static com.zjlanyun.eplus.view.report.UtilConstants.CLASS_TOP;
import static com.zjlanyun.eplus.view.report.UtilConstants.DEFAULT_CHECK;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_ACTION;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_DP2PX;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_HF_XVALUE;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_HF_YVALUE;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_JSON_DATA;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_NAME;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_RA_MODELID;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_RA_NAME;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_RA_PROPERTYNAME;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_RA_TABLENAME;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_RA_TDOMAIN;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_RA_VIEWMODE;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_TA_JSON_CONDITION;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_TA_JSON_CONDITIONSQL;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_TA_JSON_TABLE;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_TA_PROPERTY;
import static com.zjlanyun.eplus.view.report.UtilConstants.KEY_TA_TDOMAIN;
import static com.zjlanyun.eplus.view.report.UtilConstants.MODEL_ID;
import static com.zjlanyun.eplus.view.report.UtilConstants.REPORT_ACTION;
import static com.zjlanyun.eplus.view.report.UtilConstants.SHOW_HISTOGRM;
import static com.zjlanyun.eplus.view.report.UtilConstants.SHOW_TABLE;
import static com.zjlanyun.eplus.view.report.UtilConstants.TABLEACTIVITY_ACTION;


/**
 * 列表布局中用户点击某个具体的属性从而跳转到该页面
 *
 * @author xiao.han
 *         created at 2017/6/26 0026 16:35
 */
public class TableActivity extends AppCompatActivity implements GalleryAdapter.ItemClickListener {
    private static final String TAG = "TableActivity";
    private TableFixHeaders mTableFixHeaders;
    ArrayList<ArrayList<String>> mList;
    private RecyclerView mRecyclerView;//横向RecyclerView
    private LinearLayout recyclerview_layout;
    //设置RecycleView上下左右间距
    private SpaceItemDecoration spaceItemDecoration;
    private String modelId;

    private List<Map<String, String>> ThirdMenuList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_table);
        initView();
    }

    /**
     * 初始化
     */
    public void initView() {
        //获取上一个的传过来的值
        Bundle bundle = this.getIntent().getExtras();
        modelId = bundle.getString(KEY_RA_TABLENAME);
        String PropertyName = bundle.getString(KEY_RA_PROPERTYNAME);
        //实例控件
        mTableFixHeaders = (TableFixHeaders) findViewById(R.id.table);
        mRecyclerView = (RecyclerView) findViewById(R.id.id_recyclerview_horizontal);
        recyclerview_layout = (LinearLayout) findViewById(R.id.recyclerview_layout);
        //设置横向recycleView间距
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(getApplication(), KEY_DP2PX, CLASS_TOP, CLASS_BOTTOM, CLASS_LEFT, CLASS_RIGHT));
        //设置横向recycleView
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(TableActivity.this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        // 设置ToolBar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(PropertyName);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        //Toolbar左边返回键监听
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        //获取数据
        //initData(modelId, TABLEACTIVITY_ACTION);
        getThirdMenu(PropertyName);
    }

    /**
     * 获取三级菜单
     * @param name
     */
    public void getThirdMenu(String name) {
        HttpRequest client = new HttpRequest(TableActivity.this, WebApi.api());
        client.getRequest().add(KEY_ACTION, REPORT_ACTION);
        client.getRequest().add(KEY_NAME, name);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                Log.d(TAG, "getThirdMenu返回的数据:" + response.get().toString());
                JSONObject jsonObject = null;
                ThirdMenuList = new ArrayList<Map<String, String>>();
                try {
                    jsonObject = new JSONObject(response.get().toString());
                    JSONArray jsonArray = jsonObject.getJSONArray("data");
                    if (jsonArray.length() > 0) {
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject myjsonObject = (JSONObject) jsonArray.get(i);
                            Map<String, String> map = new HashMap<String, String>();
                            map.put(KEY_RA_NAME, myjsonObject.optString(KEY_RA_NAME));
                            map.put(KEY_RA_MODELID, myjsonObject.optString(KEY_RA_MODELID));
                            map.put(KEY_RA_VIEWMODE, myjsonObject.optString(KEY_RA_VIEWMODE));
                            map.put(KEY_RA_TDOMAIN, myjsonObject.optString(KEY_RA_TDOMAIN));

                            //有条件，即有三级菜单
                            recyclerview_layout.setVisibility(View.VISIBLE);
                            mRecyclerView.setVisibility(View.VISIBLE);
                            ThirdMenuList.add(map);
                            GalleryAdapter mAdapter = new GalleryAdapter(ThirdMenuList);
                            mAdapter.setOnClickListener(TableActivity.this);
                            mRecyclerView.setAdapter(mAdapter);
                            //默认显示第一个数据
                            initData(ThirdMenuList.get(0).get(KEY_RA_MODELID),
                                    TABLEACTIVITY_ACTION,ThirdMenuList.get(0).get(KEY_RA_TDOMAIN),true);
                        }
                    }else {
                        recyclerview_layout.setVisibility(View.GONE);
                        mRecyclerView.setVisibility(View.GONE);
                        initData(modelId,TABLEACTIVITY_ACTION,null,false);
                        Log.d(TAG,"没有三级菜单，直接显示数据");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 获取表格数据
     * @param modelId 模型id
     * @param action 动作
     * @param tdomain 附加sql语句
     * @param isExit 是有有附加sql语句
     */
    public void initData(String modelId, String action ,String tdomain,boolean isExit) {
        HttpRequest client = new HttpRequest(TableActivity.this, WebApi.api());
        client.getRequest().add(KEY_ACTION, action);
        client.getRequest().add(MODEL_ID, modelId);
        if (isExit)
            client.getRequest().add("tdomain", tdomain);

        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                super.onSucceed(what, response);
                Log.d(TAG, "返回的数据:" + response.get().toString());
                parseData(response.get().toString());
            }

            @Override
            public void onFailed(int what, Response<JSONObject> response) {
                super.onFailed(what, response);
//                Log.d(TAG, "11111111返回的数据:" + response.get().toString());
            }
        });

    }

    /**
     * 解析数据，封装数据
     *
     * @author xiao.han
     * created at 2017/6/23 0023 17:08
     */
    public void parseData(String Json) {
        try {
            mList = new ArrayList<>();
            JSONObject jsonObject = new JSONObject(Json);
            JSONArray jsonArray = jsonObject.getJSONArray(KEY_JSON_DATA);
            //获取展示数据
            JSONObject table = (JSONObject) jsonArray.get(0);
            JSONArray resultJsonArray = table.getJSONArray(KEY_TA_JSON_TABLE);
            for (int i = 0; i < resultJsonArray.length(); i++) {
                ArrayList<String> arrayList = new ArrayList<>();
                JSONArray a = (JSONArray) resultJsonArray.get(i);
                for (int j = 0; j < a.length(); j++) {
                    arrayList.add(j, a.get(j).toString());
                }
                mList.add(arrayList);
            }
            myHandle.sendEmptyMessage(SHOW_TABLE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    Handler myHandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                //展示表格·
                case SHOW_TABLE:
                    TableDataAdapter tableDataAdapter = new TableDataAdapter(TableActivity.this, mList, 40, 16);
                    mTableFixHeaders.setAdapter(tableDataAdapter);
                    break;
                default:break;
            }



        }
    };

    @Override
    public void itemClick(int position, String PropertyName, String sql,String viewModel,String model_id) {
        Log.d(TAG, "点击了上方菜单,postion = " + position + "....PropertyName = " + PropertyName
                + "....sql = " + sql + "....viewModel:" + viewModel + "...model_id:"+model_id);
        initData(model_id,TABLEACTIVITY_ACTION,sql,true);

    }


}
